package com.feisuanyz.service.impl;

import com.feisuanyz.dto.NotificationDTO;
import com.feisuanyz.dto.NotificationQuery;
import com.feisuanyz.dto.RestResult;
import com.feisuanyz.entity.NotificationManagementDO;
import com.feisuanyz.entity.OperationLog;
import com.feisuanyz.entity.UserPermissionDO;
import com.feisuanyz.query.UpdateNotificationStatusQuery;
import com.feisuanyz.query.ViewNotificationQuery;
import com.feisuanyz.repository.NotificationManagementRepository;
import com.feisuanyz.repository.OperationLogRepository;
import com.feisuanyz.repository.UserPermissionRepository;
import com.feisuanyz.service.NotificationService;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *   通知管理业务逻辑实现类
 * </p>
 * @author 23265
 */
@Service
@Slf4j
public class NotificationServiceImpl implements NotificationService {

    @Autowired
    private NotificationManagementRepository notificationManagementRepository;

    @Autowired
    private UserPermissionRepository userPermissionRepository;

    @Autowired
    private OperationLogRepository operationLogRepository;

    @Autowired
    private ModelMapper modelMapper;

    @Override
    @Transactional(readOnly = true)
    public NotificationDTO viewNotification(ViewNotificationQuery query) {
        return notificationManagementRepository.findById(query.getNotificationId())
                .map(this::convertToDTO)
                .orElseThrow(() -> new RuntimeException("通知不存在"));
    }

    @Override
    @Transactional
    public NotificationDTO updateNotificationStatus(UpdateNotificationStatusQuery query, Integer userId) {
        // 检查用户是否有权限更新通知
        List<UserPermissionDO> permissions = userPermissionRepository.findByUserIdAndPermissionLevels(userId, List.of(UserPermissionDO.PermissionLevel.ADMIN, UserPermissionDO.PermissionLevel.EDITOR));
        if (permissions.isEmpty()) {
            throw new RuntimeException("用户无权限");
        }

        NotificationManagementDO notification = notificationManagementRepository.findById(query.getNotificationId())
                .orElseThrow(() -> new RuntimeException("通知不存在"));

        notification.setIsActive(query.getIsActive());
        notification.setUpdateTime(LocalDateTime.now());
        notification.setUpdateBy(userId);

        try {
            notificationManagementRepository.save(notification);
            return convertToDTO(notification);
        } catch (Exception e) {
            log.error("更新通知状态失败", e);
            throw new RuntimeException("系统异常");
        }
    }

    @Override
    @Transactional
    public RestResult<Void> createNotification(NotificationQuery notificationQuery) {
        try {
            NotificationManagementDO notificationManagement = modelMapper.map(notificationQuery, NotificationManagementDO.class);
            notificationManagement.setCreateTime(LocalDateTime.now());
            notificationManagementRepository.save(notificationManagement);

            OperationLog operationLog = new OperationLog();
            operationLog.setNotificationId(notificationManagement.getNotificationId());
            operationLog.setOperationType(OperationLog.OperationType.CREATE);
            operationLog.setDetails("Created notification with ID: " + notificationManagement.getNotificationId());
            operationLog.setCreateBy(notificationQuery.getCreateBy());
            operationLog.setCreateTime(LocalDateTime.now());

            operationLogRepository.save(operationLog);

            return new RestResult<>("000000", "调用成功", null);
        } catch (Exception e) {
            log.error("Failed to create notification", e);
            return new RestResult<>("999999", "系统异常", null);
        }
    }

    @Override
    @Transactional
    public RestResult<Void> editNotification(NotificationQuery notificationQuery) {
        try {
            NotificationManagementDO existingNotification = notificationManagementRepository.findById(notificationQuery.getNotificationId())
                    .orElseThrow(() -> new RuntimeException("Notification not found"));

            if (notificationQuery.getMessage() != null) {
                existingNotification.setMessage(notificationQuery.getMessage());
            }
            if (notificationQuery.getIsActive() != null) {
                existingNotification.setIsActive(notificationQuery.getIsActive());
            }
            existingNotification.setUpdateBy(notificationQuery.getUpdateBy());

            notificationManagementRepository.save(existingNotification);

            OperationLog operationLog = new OperationLog();
            operationLog.setNotificationId(existingNotification.getNotificationId());
            operationLog.setOperationType(OperationLog.OperationType.EDIT);
            operationLog.setDetails("Updated notification with ID: " + existingNotification.getNotificationId());
            operationLog.setCreateBy(notificationQuery.getUpdateBy());
            operationLog.setCreateTime(LocalDateTime.now());

            operationLogRepository.save(operationLog);

            return new RestResult<>("000000", "调用成功", null);
        } catch (Exception e) {
            log.error("Failed to edit notification", e);
            return new RestResult<>("999999", "系统异常", null);
        }
    }

    @Override
    @Transactional
    public RestResult<Void> deleteNotification(Integer notificationId, Integer deleteBy) {
        try {
            NotificationManagementDO notificationManagement = notificationManagementRepository.findById(notificationId)
                    .orElseThrow(() -> new RuntimeException("Notification not found"));

            notificationManagementRepository.delete(notificationManagement);

            OperationLog operationLog = new OperationLog();
            operationLog.setNotificationId(notificationId);
            operationLog.setOperationType(OperationLog.OperationType.DELETE);
            operationLog.setDetails("Deleted notification with ID: " + notificationId);
            operationLog.setCreateBy(deleteBy);
            operationLog.setCreateTime(LocalDateTime.now());

            operationLogRepository.save(operationLog);

            return new RestResult<>("000000", "调用成功", null);
        } catch (Exception e) {
            log.error("Failed to delete notification", e);
            return new RestResult<>("999999", "系统异常", null);
        }
    }

    private NotificationDTO convertToDTO(NotificationManagementDO notification) {
        NotificationDTO dto = modelMapper.map(notification, NotificationDTO.class);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        dto.setCreateTime(notification.getCreateTime().format(formatter));
        dto.setUpdateTime(notification.getUpdateTime().format(formatter));
        return dto;
    }
}